<?php

namespace app\common\listener;

use app\manage\model\Config;
use app\enterprise\model\{Friend as FriendModel, User, User as UserModel};
use think\db\Where;

// 监听用户注册后的操作
class UserRegister
{

    public function handle(User $user, $data)
    {
        try { // 赋予新注册用户管理元好友
            $systemInfo = Config::getSystemInfo();
            if (!empty($systemInfo['sysInfo']['isBindAdmin'])) {
                if(isset($data['role'])){
                    $role = $data['role'];
                }else{
                    $role = 2;
                }
                $where = [
                    'role' => $role,
                    'delete_time' => 0,
                    'status' => 1
                ];
                $userIds = UserModel::where($where)->column('user_id');//查询当前角色
                $friendWhere[] = ['friend_user_id', 'in', $userIds];
                $friendWhere[] = ['create_user', '=', $data['user_id']];
                $friendOrWhere[] = ['friend_user_id', '=', $data['user_id']];
                $friendOrWhere[] = ['create_user', 'in', $userIds];
                $friendList = FriendModel::where($friendWhere)->whereOr($friendOrWhere)->column('friend_user_id,create_user');//查询当前管理员是否绑定过该用户
                $friendColumn = [];
                foreach ($friendList as $value) {
                    $friendColumn[$value['friend_user_id'] . '_' . $value['create_user']] = 1;
                }
                $add = [];
                foreach ($userIds as $userId) {
                    if($userId == $data['user_id']) continue;//自己无须添加
                    if (empty($friendColumn[$userId . '_' . $data['user_id']])) {//正向添加管理好友
                        $add[] = [
                            'friend_user_id' => $userId,
                            'create_user' => $data['user_id'],
                            'status' => 1,
                            'is_self' => 0,
                            'update_time' => time(),
                            'create_time' => time()
                        ];
                    }
                    if (empty($friendColumn[$data['user_id'] . '_' . $userId])) {//反向添加管理好友
                        $add[] = [
                            'friend_user_id' => $data['user_id'],
                            'create_user' => $userId,
                            'status' => 1,
                            'is_self' => 0,
                            'update_time' => time(),
                            'create_time' => time()
                        ];
                    }
                }
                FriendModel::insertAll($add);//添加用户管理好友
                FriendModel::where($friendWhere)->whereOr($friendOrWhere)->update(['status' => 1]);
            }
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}